<template>
	<view class="scan-container">
		<!-- 相机区域 -->
		<camera v-if="showCamera" device-position="back" :flash="flashOn ? 'on' : 'off'" class="camera-view"
			@error="cameraError">
			<!-- 扫描框 -->
			<view class="scan-box" :class="{ 'scanning': isScanning }">
				<view class="corner corner-top-left"></view>
				<view class="corner corner-top-right"></view>
				<view class="corner corner-bottom-left"></view>
				<view class="corner corner-bottom-right"></view>
				<view class="scan-line"></view>
			</view>

			<!-- 状态提示 -->
			<view class="scan-tips">
				<text class="tips-text">{{tipText}}</text>
				<text v-if="isScanning" class="scan-indicator">● 自动扫描中...</text>
			</view>
		</camera>

		<!-- 底部操作 -->
		<!-- <view class="bottom-bar">
			<view class="action-btn" @click="chooseImage">
				<text class="icon">📷</text>
				<text class="btn-text">相册</text>
			</view>
			<view class="capture-btn" @click="manualCapture">
				<view class="capture-inner"></view>
			</view>
			<view class="action-btn" @click="toggleAutoScan">
				<text class="icon">{{isScanning ? '⏸' : '▶'}}</text>
				<text class="btn-text">{{isScanning ? '暂停' : '开始'}}</text>
			</view>
		</view> -->
	</view>
</template>

<script>
	import {
		baseURL,
		imgURL
	} from '@/api/config'

	export default {
		data() {
			return {
				showCamera: true,
				flashOn: false,
				tipText: '正在启动自动扫描...',
				isScanning: false,
				cameraContext: null,
				isProcessing: false,
				autoTimer: null,
				lastImagePath: '',
				lastCaptureTime: 0
			};
		},
		onLoad() {
			setTimeout(() => {
				this.initCamera();
			}, 500);
		},
		onUnload() {
			this.stopAutoScan();
		},
		methods: {
			initCamera() {
				// #ifdef APP-PLUS || MP-WEIXIN
				this.cameraContext = uni.createCameraContext();
				this.tipText = '自动扫描已就绪';
				this.startAutoScan();
				// #endif
				// #ifndef APP-PLUS || MP-WEIXIN
				this.tipText = '当前环境不支持相机';
				this.showCamera = false;
				// #endif
			},

			startAutoScan() {
				if (this.autoTimer) return;
				this.isScanning = true;
				setTimeout(() => {
					this.autoCapture();
				}, 5000);
				this.autoTimer = setInterval(() => {
					this.autoCapture();
				}, 7000);
			},

			stopAutoScan() {
				if (this.autoTimer) {
					clearInterval(this.autoTimer);
					this.autoTimer = null;
				}
				this.isScanning = false;
			},

			autoCapture() {
				const now = Date.now();
				if (now - this.lastCaptureTime < 1000) return;
				this.lastCaptureTime = now;
				if (!this.cameraContext || this.isProcessing) return;
				this.isProcessing = true;

				// #ifdef APP-PLUS || MP-WEIXIN
				this.cameraContext.takePhoto({
					quality: 'normal',
					success: (res) => {
						if (this.lastImagePath === res.tempImagePath) {
							this.isProcessing = false;
							return;
						}
						this.lastImagePath = res.tempImagePath;
						this.processImage(res.tempImagePath, false);
					},
					fail: (err) => {
						console.error('拍照失败:', err);
						this.isProcessing = false;
						if (this.isScanning) {
							setTimeout(() => this.autoCapture(), 1000);
						}
					}
				});
				// #endif
			},

			// ✅ 修改为async方法，支持await
			// ✅ 修改为async方法，支持await
			async processImage(imagePath, isManual) {
				console.log('开始处理图片:', imagePath); // 调试日志
				uni.showLoading({
					title: '识别中...'
				});

				try {
					// 模拟识别过程
					await new Promise(resolve => setTimeout(resolve, 1500));

					const recognizeResult = this.mockRecognize(imagePath);
					console.log('识别结果:', recognizeResult); // 调试日志

					const isSuccess = !recognizeResult.includes('未识别') && !recognizeResult.includes('模糊');

					if (isSuccess) {
						this.stopAutoScan();
						this.tipText = '识别成功，上传图片中...';

						try {
							// ✅ 上传图片并获取URL
							uni.showLoading({
								title: 'loading...'
							});
							console.log('准备上传文件:', imagePath); // 调试日志 
							uni.uploadFile({
								url: baseURL+'/common/upload/', //   // 
								filePath: imagePath, // 必须是完整路径
								name: 'files',
								header: { 
									"Content-Type": "application/x-www-form-urlencoded",
								},
								success: (res) => {
									uni.hideLoading();
									console.log('上传响应:', res); // 调试用
									const data = JSON.parse(res.data);
									if (data.code == 200) {
										// console.log(data.url)
										// const fullUrl = data.data.startsWith('http') ? data.data :
										// 	imgURL +
										// 	data.data;
										console.log('上传成功URL:', data.data); // 调试用 

										// ✅ 使用上传后的URL跳转
										const url =
											`/pages/two/dakaDetail?imagePath=${data.data}`;
										uni.redirectTo({
											url: url
										});
									} else {

									}
								},
								fail: (err) => {
									console.error('上传失败:', err); // 调试用
									reject(new Error(err.errMsg || '上传失败'));
								}
							});


						} catch (uploadError) {
							uni.hideLoading();
							console.error('上传失败:', uploadError);
							uni.showToast({
								title: '图片上传失败:' + uploadError.message,
								icon: 'none'
							});
							this.isProcessing = false;

							// 上传失败后继续扫描
							if (this.isScanning) {
								setTimeout(() => this.autoCapture(), 1000);
							}
						}
					} else {
						this.isProcessing = false;
						this.tipText = '未识别到目标，继续扫描...';
						console.log('识别失败，继续扫描'); // 调试日志

						setTimeout(() => {
							this.tipText = '自动扫描中...';
						}, 2000);
					}
				} catch (error) {
					uni.hideLoading();
					this.isProcessing = false;
					console.error('处理图片失败:', error);
					uni.showToast({
						title: '处理失败，请重试',
						icon: 'none'
					});
				}
			},



			mockRecognize(imagePath) {
				// 测试时总是返回成功，方便验证功能
				return `✅ 识别到打卡目标\n时间：${new Date().toLocaleString()}`;

				// 正式环境使用随机结果（需要时取消注释）
				/*
				const mockResults = [
				  '✅ 识别到打卡目标：\n办公室工位',
				  '✅ 识别到打卡目标：\n会议室门禁',
				  '❌ 未识别到有效内容',
				  '❌ 图像模糊'
				];
				return mockResults[Math.floor(Math.random() * mockResults.length)];
				*/
			},

			manualCapture() {
				if (this.isProcessing) {
					uni.showToast({
						title: '处理中...',
						icon: 'loading'
					});
					return;
				}
				this.stopAutoScan();
				this.autoCapture();
			},

			chooseImage() {
				if (this.isProcessing) {
					uni.showToast({
						title: '处理中...',
						icon: 'loading'
					});
					return;
				}
				this.stopAutoScan();
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'],
					sourceType: ['album'],
					success: (res) => {
						this.processImage(res.tempFiles[0].tempFilePath, true);
					}
				});
			},

			toggleAutoScan() {
				if (this.isScanning) {
					this.stopAutoScan();
					this.tipText = '自动扫描已暂停';
				} else {
					this.startAutoScan();
					this.tipText = '自动扫描已恢复';
				}
			},

			cameraError(e) {
				console.error('相机错误:', e);
				this.tipText = '相机无法使用，请检查权限';
				this.stopAutoScan();
				uni.showModal({
					title: '提示',
					content: '相机启动失败，请从相册选择图片',
					showCancel: false
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.scan-container {
		width: 100vw;
		height: 100vh;
		position: relative;
		background: #000;
	}

	.camera-view {
		width: 100%;
		height: calc(100vh - 200rpx);
		position: relative;
	}

	/* ✅ 扫描框样式 - 四角已加粗 */
	.scan-box {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 600rpx;
		height: 400rpx;
		border: 2rpx solid rgba(0, 255, 157, 0.3);

		&.scanning {
			border-color: rgba(0, 255, 157, 0.6);
			box-shadow: 0 0 20rpx rgba(0, 255, 157, 0.3);
		}

		/* ✅ 加粗的四角边框 - 从4rpx改为8rpx */
		.corner {
			position: absolute;
			width: 40rpx;
			height: 40rpx;
			border: 8rpx solid #00ff9d; // 加粗：4rpx → 8rpx

			/* ✅ 调整位置偏移量 - 从-4rpx改为-8rpx */
			&-top-left {
				top: -8rpx;
				left: -8rpx;
				border-right: none;
				border-bottom: none;
			}

			&-top-right {
				top: -8rpx;
				right: -8rpx;
				border-left: none;
				border-bottom: none;
			}

			&-bottom-left {
				bottom: -8rpx;
				left: -8rpx;
				border-right: none;
				border-top: none;
			}

			&-bottom-right {
				bottom: -8rpx;
				right: -8rpx;
				border-left: none;
				border-top: none;
			}
		}

		.scan-line {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 4rpx;
			background: linear-gradient(to bottom, #00ff9d, rgba(0, 255, 157, 0.3));
			animation: scanMove 2s linear infinite;
			box-shadow: 0 0 20rpx #00ff9d;
		}
	}

	@keyframes scanMove {
		0% {
			top: 0;
		}

		100% {
			top: 100%;
		}
	}

	/* 提示文字 */
	.scan-tips {
		position: absolute;
		bottom: 80rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 80%;
		text-align: center;

		.tips-text {
			color: #fff;
			font-size: 28rpx;
			background: rgba(0, 0, 0, 0.5);
			padding: 12rpx 24rpx;
			border-radius: 30rpx;
			display: block;
			margin-bottom: 20rpx;
		}

		.scan-indicator {
			color: #00ff9d;
			font-size: 24rpx;
			display: block;
			animation: blink 1.5s ease-in-out infinite;
		}
	}

	@keyframes blink {

		0%,
		100% {
			opacity: 1;
		}

		50% {
			opacity: 0.3;
		}
	}

	/* 底部操作栏 */
	.bottom-bar {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 200rpx;
		background: rgba(0, 0, 0, 0.8);
		display: flex;
		justify-content: space-around;
		align-items: center;

		.action-btn {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx;

			.icon {
				font-size: 48rpx;
				color: #fff;
				margin-bottom: 8rpx;
			}

			.btn-text {
				font-size: 24rpx;
				color: #ccc;
			}
		}

		.capture-btn {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			background: rgba(255, 255, 255, 0.9);
			display: flex;
			justify-content: center;
			align-items: center;

			.capture-inner {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				background: #00ff9d;
			}
		}
	}
</style>